package com.ms.pda.net

import android.text.TextUtils
import com.blankj.utilcode.util.JsonUtils
import com.google.gson.JsonSyntaxException
import rxhttp.wrapper.exception.HttpStatusCodeException
import rxhttp.wrapper.exception.ParseException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

class ResponseError(throwable: Throwable) {

    var errorCode = 0//仅指服务器返回的错误码
    var errorMsg: String? = null //错误文案，网络错误、请求失败错误、服务器返回的错误等文案
    var throwable: Throwable? = null//异常信息

    init {
        this.throwable = throwable
        var errorMsg: String?
        if (throwable is UnknownHostException) {
            errorCode = -1
            errorMsg = "网络异常，请检查网络连接"
        } else if (throwable is SocketTimeoutException || throwable is TimeoutException) {
            errorCode = -1
            errorMsg = "请求超时"
        } else if (throwable is ConnectException) {
            errorCode = -1
            errorMsg = "网络异常，请检查网络连接"
        } else if (throwable is HttpStatusCodeException) { //请求失败异常
            val errorCode = throwable.getLocalizedMessage()
            this.errorCode = errorCode?.toInt() ?: 0
            errorMsg = JsonUtils.getString(throwable.result, "msg")
        } else if (throwable is JsonSyntaxException) { //请求成功，但Json语法异常,导致解析失败
            errorCode = -1
            errorMsg = "数据解析异常"
        } else if (throwable is ParseException) { // ParseException异常表明请求成功，但是数据不正确
            val errorCode = throwable.getLocalizedMessage()
            this.errorCode = errorCode?.toInt() ?: 0
            errorMsg = throwable.message
            if (TextUtils.isEmpty(errorMsg)) errorMsg = errorCode //errorMsg为空，显示errorCode
        } else {
            errorMsg = throwable.message
        }
        this.errorMsg = errorMsg
    }

}